<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'
import { adminUpdatePwdService } from '@/api/admin.js'

import { useRouter } from 'vue-router';
const router = useRouter();

const tokenStore = useTokenStore()

const updatePwdForm = ref({
  oldPwd: '',
  newPwd: '',
  rePwd: ''
})

const rules = {
  oldPwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, max: 16, message: '密码长度必须在8-16位之间', trigger: 'blur' },
    { 
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,16}$/,
      message: '密码必须包含大小写字母、数字和特殊字符',
      trigger: 'blur'
    }
  ],
  rePwd: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== updatePwdForm.value.newPwd) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ]
}

const updatePassword = async () => {
  // 在发送请求之前关闭所有消息
  ElMessage.closeAll();

  try {
    const pwdData = {
      old_pwd: updatePwdForm.value.oldPwd,
      new_pwd: updatePwdForm.value.newPwd,
      re_pwd: updatePwdForm.value.rePwd
    }
    await adminUpdatePwdService(pwdData, tokenStore.token)
    ElMessage.success('密码修改成功，请重新登录')
    router.push('/login')
  } catch (error) {
    // 在这里捕获错误并显示消息
    ElMessage.error('密码修改失败，请重新确认信息')
  }
}

</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>修改密码</span>
      </div>
    </template>
    <el-form :model="updatePwdForm" :rules="rules" ref="updatePwdFormRef" label-width="100px" size="large">
      <el-form-item label="原密码" prop="oldPwd">
        <el-input v-model="updatePwdForm.oldPwd" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="updatePwdForm.newPwd" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="rePwd">
        <el-input v-model="updatePwdForm.rePwd" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatePassword">提交修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>
.page-container {
    width: 50%;
    margin: auto;
}
.header {
    font-size: larger;
    font-weight: bold;
}

.el-input{
  width: 50%;
}
</style>
